package top.kaoshanji.p1ch07a;

import org.apache.hc.core5.http.ContentType;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * 代码清单-p1ch07a-238页a：使用会话跟踪API
 * URL访问地址：/shoppingCartViewerSession
 * @author kaoshanji
 * ^_^
 * create time 2025/4/5 11:10
 */
public class ShoppingCartViewerSession extends HttpServlet {

    // 会话属性
    private static final String SESSION_ATTRIBUTE_CART_ITEMS = "cart.items";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求对象的编码
        req.setCharacterEncoding(StandardCharsets.UTF_8.name());

        // 设置响应对象的编码和内容格式
        resp.setContentType(ContentType.TEXT_HTML.toString());
        PrintWriter out = resp.getWriter();

        // 取得当前会话对象，必要时生成一个
        HttpSession session = req.getSession();

        // 购物车项目在会话对象中
        String[] items = (String[]) session.getAttribute(SESSION_ATTRIBUTE_CART_ITEMS);

        out.println("<HTML><HEAD><TITLE>SessionTracker</TITLE></HEAD>");
        out.println("<BODY><H1>Session Tracking Demo</H1>");

        // 打印当前购物车项
        out.println("You currently have the following items in your cart:<BR>");
        if (items == null) {
            out.println("<B>None</B>");
        } else {
            out.println("<UL>");
            for (int i = 0; i < items.length; i++) {
                out.println("<LI>" + items[i]);
            }
            out.println("</UL>");
        }

        // 询问添加项目还是结账
        out.println("<FORM ACTION=\"" + resp.encodeURL("/servlet/ShoppingCart") + "\" METHOD=POST>");
        out.println("Would you like to<BR>");
        out.println("<INPUT TYPE=SUBMIT VALUE=\" Add More Items \">");
        out.println("<INPUT TYPE=SUBMIT VALUE=\" Check Out \">");
        out.println("</FORM>");

        // 提供帮助网页，必要时编码
        out.println("For help, click <A HREF=\"" +
                resp.encodeURL("/servlet/Help?topic=ShoppingCartViewer") + "\">here</A>");

        out.println("</BODY></HTML>");

    }

}
